package scct.zhurui.dao;

import scct.zhurui.model.GoodsType;
import scct.zhurui.utils.DBUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class TypeDao {
    public List<GoodsType>getAllType(){
        List<GoodsType> list=new ArrayList<>();
        Connection conn = DBUtils.getConnection();
        String sql ="select * from  sm_goodstype;";
        PreparedStatement pstmt=null;
        try {
            pstmt=conn.prepareStatement(sql);
            ResultSet rs=pstmt.executeQuery();
            while (rs.next()){
                int id =rs.getInt("id");
                String name=rs.getString("name");
                String remark =rs.getString("remark");
                list.add(new GoodsType(id,name,remark));
                DBUtils.closeConnection(conn);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return list;
    }
    public boolean addType(String name ,String remark){
        int result=0;
        Connection conn=DBUtils.getConnection();
        String sql ="insert into sm_goodstype values(null,?,?)";
        try {
            PreparedStatement pstmt=conn.prepareStatement(sql);
            pstmt.setString(1,name);
            pstmt.setString(2,remark);
            result=pstmt.executeUpdate();
            DBUtils.closeConnection(conn);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return result>0;
    }
    public boolean updateType (int id,String name ,String remark){
        int result=0;
        Connection conn=DBUtils.getConnection();
        String update_sql="update sm_goodstype set name=?,remark=? where id=?";
        try {
            PreparedStatement pstmt=conn.prepareStatement(update_sql);
            pstmt.setString(1,name);
            pstmt.setString(2,remark);
            result= pstmt.executeUpdate();
            DBUtils.closeConnection(conn);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return result>0;
    }
//    public  boolean isDumptype(String name){
//        int count =0;
//        Connection conn=DBUtils.getConnection();
//        String sql="";
//        try {
//            PreparedStatement pstmt=conn.prepareStatement(sql);
//            pstmt.setString(1,name);
//            ResultSet rs=pstmt.executeQuery();
//            if (rs.next()){
//                count=1;
//            }
//            DBUtils.closeConnection(conn);
//
//        } catch (SQLException e) {
//            throw new RuntimeException(e);
//        }
//        return count>0;
//    }
}
